package com.sniper.web.shiro.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sniper.utils.HttpRequestUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class KickoutSessionControlFilter extends AccessControlFilter {

    //记录登录用户ip
    public static final String OUT_IP = "out_ip";
    //登录用户登录时间
    public static final String OUT_TIME = "out_time";
    //缓存名称
    public static final String CACHE_NAME = "surveyAdminRight";
    //被提出的标志
    private static final String KICK_OUT = "kickout";
    // 踢出后到的地址
    private String kickoutUrl;
    // 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
    private boolean kickoutAfter = false;
    // 同一个帐号最大会话数 默认1
    private int maxSession = 1;

    private Cache<String, Deque<Serializable>> cache;

    private CacheManager cacheManager;
    private SessionManager sessionManager;

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public void setCacheManager(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
        this.cache = this.cacheManager.getCache(CACHE_NAME);
    }

    /**
     * 是否允许访问，
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        Subject subject = getSubject(request, response);
        //如果用户没有认证
        if (subject.getPrincipal() == null) {
            return true;
        }

        Session session = subject.getSession();
        //记录用户的ip，用户登录时间在登陆的时候已经写入
        //System.out.println("当前session：" + session.getAttribute(KICK_OUT));
        String username = (String) subject.getPrincipal();
        Serializable sessionId = session.getId();
        //检查一遍是否被强制退出了
        if (session.getAttribute(KICK_OUT) != null) {
            if (HttpRequestUtils.isAjax((HttpServletRequest) request)) {
                Map<String, String> map = new HashMap<>();
                map.put("msg", "有人在其他地方登陆了。");
                out(response, map);
            }
            return false;
        }

        // TODO Shrio 单一用户登录 同步控制
        Deque<Serializable> deque = cache.get(username);
        if (deque == null) {
            deque = new LinkedList<>();
            //保存自己
            deque.add(sessionId);
            cache.put(username, deque);
        }

        // 如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if (!deque.contains(sessionId) && session.getAttribute(KICK_OUT) == null) {
            deque.push(sessionId);
        }
        //System.out.println("当前sessionid：" + sessionId.toString());
        //System.out.println("列队：" + deque.toString());
        // 如果队列里的sessionId数超出最大会话数，开始踢人
        if (deque.size() > maxSession) {
            //拿走的session
            Serializable outSessionId;
            //留下的session
            Serializable inSessionId;
            if (kickoutAfter) {
                // 踢出最后一个
                outSessionId = deque.getLast();
                inSessionId = deque.getFirst();
            } else {
                // 踢出第一个
                outSessionId = deque.getFirst();
                inSessionId = deque.getLast();
            }
            //如果被提出的session是我的
            if (outSessionId.equals(sessionId)) {
                session.setAttribute(KICK_OUT, true);
                //读取留下的用户信息告诉用户是谁在登录
                //读取留下的session
                Session inSession = this.sessionManager.getSession(new DefaultSessionKey(inSessionId));
                //下面的信息都在登录页面设置了
                session.setAttribute(OUT_IP, inSession.getAttribute(OUT_IP));
                session.setAttribute(OUT_TIME, inSession.getAttribute(OUT_TIME));
                deque.remove(sessionId);
                return false;
            }
        }
        return true;
    }

    /**
     * 不允许访问之后的处理,上面返回false就会执行下面的代码
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        Session session = subject.getSession();
        // 如果被踢出了，直接退出，重定向到踢出后的地址
        System.out.println("踢出：" + session.getId());
        saveRequest(request);
        subject.logout();
        WebUtils.redirectToSavedRequest(request, response, kickoutUrl + "?loginError=true");
        //WebUtils.issueRedirect(request, response, kickoutUrl);
        return false;
    }

    /**
     * 直接输出信息
     *
     * @param response
     * @param resultMap
     * @throws IOException
     */
    private void out(ServletResponse response, Map<String, String> resultMap)
            throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(resultMap);
            out.println(json);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}